package com.css.dzj.dzjap.modules.enterprise.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjap.common.audit.service.SysAuditService;
import com.css.dzj.dzjap.common.util.BeanUtil;
import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.HttpClientUtil;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.modules.enterprise.entity.ApEnterpriseCreditEntity;
import com.css.dzj.dzjap.modules.enterprise.service.EnterpriseService;
import com.css.dzj.dzjap.modules.publick.entity.ApPublicEntity;
import com.css.dzj.dzjap.modules.publick.service.PublicService;
import com.querydsl.core.QueryResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/enterPrise")
public class EnterpriseController {

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private PublicService publicService;

    @Value("${ZFJG_URL}")
    private String zfjgUrl;

    @Autowired
    private SysAuditService sysAuditService;
    @Autowired
    private HttpServletRequest request;
    /**
     * 查询评价单位或建设单位信用信息表
     */
    @GetMapping(value = "/getEnterPrise")
    public R getEnterPrise(@RequestParam("enterpriseCreditId") String enterpriseCreditId,
                           @RequestParam("enterpriseCredittype") String enterpriseCredittype){
        String s;
        try{
            ApEnterpriseCreditEntity enterPrise = enterpriseService.getEnterPrise(enterpriseCreditId, enterpriseCredittype);
            s = JSON.toJSONString(enterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.SELETE,s,request);
            return R.ok().put("data",enterPrise);
        }catch (Exception e){
            e.printStackTrace();
            s = JSON.toJSONString(enterpriseCreditId);
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.SELETE,s,e,request);
            return R.error("操作失败");
        }

    }



    /**
     * 添加评价单位或建设单位信用信息表
     */
    @PostMapping(value = "/addEnterPrise")
    public R addEnterPrise(@RequestBody ApEnterpriseCreditEntity enterPrise) {

        if (StringUtils.isEmpty(enterPrise.getEnterpriseName()) || StringUtils.isEmpty(enterPrise.getEnterpriseIdNumber())
                || StringUtils.isEmpty(enterPrise.getEnterpriseScore()) || StringUtils.isEmpty(enterPrise.getEnterpriseClassification()) || enterPrise.getAssessmentDate() == null
                || StringUtils.isEmpty(enterPrise.getAssessmentAuthority()) || StringUtils.isEmpty(enterPrise.getEnterpriseScoreNumber())) {

            return R.error("必填字段为空");
        }
        String s;
        try {
            String flag = enterpriseService.addEnterPrise(enterPrise);
            if (!"0".equals(flag)) {
                R r = new R();
                r.put("code", 200);
                r.put("msg", "操作成功");
                r.ok().put("data", flag);
                s = JSON.toJSONString(enterPrise);
                sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.ADD,s,request);
                return r;
            } else {
                return R.error("操作失败");
            }
        }catch (Exception e){
            s = JSON.toJSONString(enterPrise);
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.ADD,s,e,request);
            return R.error(e.getMessage());
        }

    }

    /**
     * 修改评价单位或建设单位信用信息表
     */
    @PostMapping(value = "/updateEnterPrise")
    public R updateEnterPrise(@RequestBody ApEnterpriseCreditEntity enterPrise ){
        String s;
        try {

            if(!StringUtils.isEmpty(enterPrise) && !StringUtils.isEmpty(enterPrise.getCreditClueReasons())) {
                if("信用分类D".equals(enterPrise.getCreditClueReasons()) || "信用分类E".equals(enterPrise.getCreditClueReasons()) ||
                        "信用分类一次性下降≥2档".equals(enterPrise.getCreditClueReasons()) || "击中特定负面".equals(enterPrise.getCreditClueReasons())){
                    String enterpriseVO = JSON.toJSONStringWithDateFormat(enterPrise,"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
                    String result = HttpClientUtil.doPostJson(zfjgUrl + "/clue/enterprisevo",enterpriseVO);
                }
            } else {
                return R.error("企业信用信息或信用线索必填字段为空");
            }

            ApEnterpriseCreditEntity ePrise = enterpriseService.getEnterPrise(enterPrise.getEnterpriseCreditId(),enterPrise.getEnterpriseCredittype());
            BeanUtil.copyBeanNotNullToBean(enterPrise, ePrise);
            ePrise.setUpdateTime(new Date());
            enterpriseService.update(ePrise);
            s = JSON.toJSONString(enterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.UPDATE,s,request);
            return R.ok("操作成功！");
        } catch (Exception e) {
            s = JSON.toJSONString(enterPrise);
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.UPDATE,s,e,request);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除评价单位或建设单位信用信息表
     */
    @PostMapping(value = "/deleteEnterPrise")
    public R deleteEnterPrise(@RequestParam("enterpriseCreditId")  String enterpriseCreditId,
                              @RequestParam("enterpriseCredittype")  String enterpriseCredittype){
        String s;
        if(enterpriseService.deleteEnterPrise(enterpriseCreditId,enterpriseCredittype)){
            s = JSON.toJSONString(enterpriseCreditId);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.DEL,s,request);
            return R.ok("操作成功!");
        }else{
            RuntimeException e = new RuntimeException("操作失败");
            s = JSON.toJSONString(enterpriseCreditId);
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.DEL,s,e,request);
            return  R.error("操作失败!");
        }
    }


    /**
     *移入评价单位或建设单位信用信息表进入黑名单
     */
    @PostMapping(value = "/moveinEnterPrise")
    public R moveinEnterPrise(@RequestBody ApEnterpriseCreditEntity enterPrise){
          if(StringUtils.isEmpty(enterPrise.getSpecause())){
            return R.error("必填字段不能为空！");
          }
        String s;
        try {

            ApPublicEntity pub = publicService.getGlTYPublick(enterPrise.getEnterpriseCreditId(),enterPrise.getEnterpriseCredittype());
            if(pub!=null){
                ApPublicEntity aPub = new ApPublicEntity();
                pub.setPublicUrl("/dzjap/enterPrise/getReEnterPrise");
                BeanUtil.copyBeanNotNullToBean(aPub, pub);
                publicService.update(aPub);
            }


            ApEnterpriseCreditEntity ePrise = enterpriseService.getEnterPrise(enterPrise.getEnterpriseCreditId(),enterPrise.getEnterpriseCredittype());
            BeanUtil.copyBeanNotNullToBean(enterPrise, ePrise);
            ePrise.setExcpresState(Constant.EXCPRES_STATE_Yes);
            ePrise.setAbnormalPutdate(new Date());
            enterpriseService.update(ePrise);
            s = JSON.toJSONString(enterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.MOVEIN,s,request);
            return R.ok("操作成功！");
        } catch (Exception e) {
            s = JSON.toJSONString(enterPrise);
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.MOVEIN,s,e,request);
            return R.error(e.getMessage());
        }
    }


    /**
     *移出评价单位或建设单位信用信息表进入黑名单
     */
     @PostMapping(value = "/moveoutEnterPrise")
     public R moveoutEnterPrise(@RequestBody ApEnterpriseCreditEntity enterPrise){
         if(StringUtils.isEmpty(enterPrise.getRemexcpres())){
             return R.error("必填字段不能为空！");
         }
         String s;
         try {

             ApPublicEntity pub = publicService.getGlTYPublick(enterPrise.getEnterpriseCreditId(),enterPrise.getEnterpriseCredittype());
             if(pub!=null){
                 ApPublicEntity aPub = new ApPublicEntity();
                 pub.setPublicUrl("/dzjap/enterPrise/getEnterPrise");
                 BeanUtil.copyBeanNotNullToBean(aPub, pub);
                 publicService.update(aPub);
             }

             ApEnterpriseCreditEntity ePrise = enterpriseService.getReEnterPrise(enterPrise.getEnterpriseCreditId(),enterPrise.getEnterpriseCredittype());
             BeanUtil.copyBeanNotNullToBean(enterPrise, ePrise);
             ePrise.setExcpresState(Constant.EXCPRES_STATE_NO);
             ePrise.setRemdate(new Date());
             enterpriseService.update(ePrise);
             s = JSON.toJSONString(enterPrise);
             sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.MOVEON,s,request);
             return R.ok("操作成功！");
         } catch (Exception e) {
             s = JSON.toJSONString(enterPrise);
             sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.MOVEON,s,e,request);
             return R.error(e.getMessage());
         }
     }


    /**
     * 查询评价单位或建设单位信用信息表黑名单
     */
    @GetMapping(value = "/getReEnterPrise")
    public R getReEnterPrise(@RequestParam("enterpriseCreditId") String enterpriseCreditId,
                           @RequestParam("enterpriseCredittype") String enterpriseCredittype){
        String s;
      try{
          ApEnterpriseCreditEntity reEnterPrise = enterpriseService.getReEnterPrise(enterpriseCreditId, enterpriseCredittype);
          s = JSON.toJSONString(reEnterPrise);
          sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.SELETE,s,request);
          return R.ok().put("data",reEnterPrise);
      }catch (Exception e){
         e.printStackTrace();
          s = JSON.toJSONString(enterpriseCreditId);
          sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.SELETE,s,e,request);
         return R.error("查询失败");
      }

    }


    /**
     *分页查询所有评价单位或建设单位信用信息表
     */
    @GetMapping(value = "/getAllEnterPrise")
    public R getAllEnterPrise(@RequestParam(required = false) Integer pageNo,
                              @RequestParam(required = false) Integer pageSize,
                              @RequestParam("enterpriseCredittype") String enterpriseCredittype, HttpServletRequest request) {
        String s="";
        try {
            PageRequest pageRequest = PageRequest.of(pageNo-1, pageSize);
            QueryResults<ApEnterpriseCreditEntity> allEnterPrise = enterpriseService.getAllEnterPrise(pageRequest, enterpriseCredittype, request);
            s = JSON.toJSONString(allEnterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,request);
            return R.ok().put("data",allEnterPrise );
        }catch (Exception e){
            e.printStackTrace();
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,e,request);
            return  R.error("分页查询失败");
        }

    }


    /**
     *分页查询所有评价单位或建设单位信用信息表黑名单
     */
    @GetMapping(value = "/getAllReEnterPrise")
    public R getAllReEnterPrise(@RequestParam(name = "pageNo" ,required = false) Integer pageNo,
                              @RequestParam(name = "pageSize" ,required = false) Integer pageSize,
                              @RequestParam("enterpriseCredittype")  String enterpriseCredittype,
                                HttpServletRequest request) {
        String s="";
        try{
            PageRequest pageRequest = PageRequest.of(pageNo-1, pageSize);
            QueryResults<ApEnterpriseCreditEntity> allReEnterPrise = enterpriseService.getAllReEnterPrise(pageRequest, enterpriseCredittype, request);
            s = JSON.toJSONString(allReEnterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,request);
            return R.ok().put("data", allReEnterPrise);
        }catch (Exception e){
            e.printStackTrace();
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,e,request);
            return  R.error("分页查询失败");
        }

    }


    /**
     *多条件分页查询所有评价单位或建设单位信用信息表
     */
    @GetMapping(value ="/getAllConEnterPrise")
    public R getAllConEnterPrise(@RequestParam(required = false) String enterpriseName,
                                 @RequestParam String enterpriseCredittype,
                                 @RequestParam String enterpriseScoreNumber,
                                 @RequestParam String enterpriseIdNumber,
                                 @RequestParam String enterpriseScore,
                                 @RequestParam String enterpriseClassification,
                                 @RequestParam String organName,
                                 @RequestParam(required = false) Integer pageNo,
                                 @RequestParam(required = false) Integer pageSize,
                                 HttpServletRequest request){
        String s="";
        try {
            PageRequest pageRequest = PageRequest.of(pageNo-1,pageSize);
            QueryResults<ApEnterpriseCreditEntity> allConEnterPrise = enterpriseService.getAllConEnterPrise(pageRequest, enterpriseCredittype, enterpriseName,
                    enterpriseScoreNumber, enterpriseIdNumber, enterpriseScore, enterpriseClassification, organName, request);
            s = JSON.toJSONString(allConEnterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,request);
            return R.ok().put("data",allConEnterPrise );
        }catch (Exception e){
            e.printStackTrace();
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,e,request);
            return  R.error("分页查询失败");

        }

    }

    /**
     *多条件分页查询所有评价单位或建设单位信用信息表黑名单
     */
    @GetMapping(value ="/getAllReConEnterPrise")
    public R getAllReConEnterPrise(@RequestParam(required = false) String enterpriseName,
                                   @RequestParam  String enterpriseCredittype,
                                   @RequestParam String enterpriseScoreNumber,
                                   @RequestParam String enterpriseIdNumber,
                                   @RequestParam String enterpriseScore,
                                   @RequestParam String enterpriseClassification,
                                   @RequestParam(required = false) Integer pageNo,
                                   @RequestParam(required = false) Integer pageSize,
                                   HttpServletRequest request){


        String s="";
        try{
            PageRequest pageRequest = PageRequest.of(pageNo-1,pageSize);
            QueryResults<ApEnterpriseCreditEntity> allReConEnterPrise = enterpriseService.getAllReConEnterPrise(pageRequest, enterpriseCredittype, enterpriseName,
                    enterpriseScoreNumber, enterpriseIdNumber, enterpriseScore, enterpriseClassification, request);
            s = JSON.toJSONString(allReConEnterPrise);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,request);
            return R.ok().put("data",allReConEnterPrise );
        }catch (Exception e){
            e.printStackTrace();
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.PAGE,s,e,request);
            return  R.error("分页查询失败");
        }

    }

    /**
     * 通过统一信用代码查询评价单位或建设单位信用信息黑名单
     */
     @GetMapping(value = "/getTyReConEnterPrise")
     public R getTyReConEnterPrise(@RequestParam String enterpriseCredittype,
                                   @RequestParam String enterpriseIdNumber){
         String s="";
         try {
             ApEnterpriseCreditEntity tyReConEnterPrise = enterpriseService.getTyReConEnterPrise(enterpriseCredittype, enterpriseIdNumber);
             s = JSON.toJSONString(tyReConEnterPrise);
             sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.SELETE,s,request);
             return R.ok().put("data",tyReConEnterPrise);
         }catch (Exception e){
             e.printStackTrace();
             sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.SELETE,s,e,request);
             return  R.error("查询失败");
         }

     }


    /**
     *添加评价单位或建设单位信用信息黑名单
     */
    @PostMapping(value = "/addReConEnterPrise")
    public R addReConEnterPrise(@RequestBody ApEnterpriseCreditEntity enterPrise) {

        if (StringUtils.isEmpty(enterPrise.getEnterpriseName()) || StringUtils.isEmpty(enterPrise.getEnterpriseIdNumber())
                || StringUtils.isEmpty(enterPrise.getEnterpriseScore()) || StringUtils.isEmpty(enterPrise.getEnterpriseClassification()) || enterPrise.getAssessmentDate() == null
                || StringUtils.isEmpty(enterPrise.getAssessmentAuthority()) || StringUtils.isEmpty(enterPrise.getEnterpriseScoreNumber()) || StringUtils.isEmpty(enterPrise.getSpecause())) {

            return R.error("必填字段为空");
        }
        String s="";
        try{
            String flag = enterpriseService.addReConEnterPrise(enterPrise);
            if (!"0".equals(flag)) {
                R r = new R();
                r.put("code", 200);
                r.put("msg", "操作成功");
                r.ok().put("data", flag);
                s = JSON.toJSONString(enterPrise);
                sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.ADD,s,request);
                return r;
            } else {
                return R.error("操作失败");
            }
        }catch (Exception e){
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.ADD,s,e,request);
            return  R.error(e.getMessage());
        }




    }


    /**
     * 批量删除
     */
    @PostMapping(value = "/deleteEnterPriseList/{enterpriseCredittype}")
    public R deleteExpertCredList(@PathVariable String enterpriseCredittype,@RequestBody String[] enterpriseCreditIds){
        String s="";
        try{
            if(enterpriseCreditIds.length<0 || enterpriseCreditIds==null || StringUtils.isEmpty(enterpriseCredittype)){

                return R.error("操作失败！");
            }
            List<ApEnterpriseCreditEntity> list = new ArrayList();

            for (String enterpriseCreditId : enterpriseCreditIds){

                ApEnterpriseCreditEntity pCred =  enterpriseService.getEnterPrise(enterpriseCreditId,enterpriseCredittype);

                if(pCred!=null){
                    pCred.setDelFlag(Constant.DELETE);//逻辑删除
                    pCred.setUpdateTime(new Date());
                    list.add(pCred);
                }else {
                    return R.error("操作失败！");
                }
            }
            if(list!=null && list.size()>0){
                enterpriseService.update(list);
            }else{
                return R.error("操作失败！");
            }
            s = JSON.toJSONString(enterpriseCreditIds);
            sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.DEL,s,request);
            return R.ok();
        }catch (Exception e){
            sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.DEL,s,e,request);
            return R.error(e.getMessage());
        }


    }

    /**
     *  等级认定
     */
    @PostMapping(value = "/updateEnterPriseList")
    public R updateEnterPriseList(@RequestBody List<ApEnterpriseCreditEntity> list ){
      String s;
     try{

         if(enterpriseService.updateEnterPriseList(list)){
             s = JSON.toJSONString(list);
             sysAuditService.saveSuccessAudit("单位信用信息表", Constant.ENTERPRISE,Constant.PT,Constant.PRISE,s,request);
             return R.ok("操作成功!");
         }else{
             return  R.error("操作失败!");
         }
        }catch (Exception e){
         s = JSON.toJSONString(list);
         sysAuditService.saveFailAudit("单位信用信息表",Constant.ENTERPRISE,Constant.PT,Constant.PRISE,s,e,request);
         return R.error(e.getMessage());
      }

    }


}
